package Utils.io;

import Utils.FsUtils;
import com.mpatric.mp3agic.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

/**
 * @author d11yu
 */
public final class Mp3Utils {
    private Mp3Utils() {
    }

    private static final String SUFFIX = "_new.mp3";
    /**
     * 修改Title
     *
     * @param path MP3文件完整路径
     * @param title 新title
     * @throws InvalidDataException
     * @throws UnsupportedTagException
     * @throws IOException
     * @throws NotSupportedException
     */
    public static void changeTitle(String path, String title) throws InvalidDataException, UnsupportedTagException, IOException, NotSupportedException {
        changeTitle(new File(path), title);
    }

    /**
     * 修改Title
     *
     * @param file MP3文件
     * @param title 新title
     * @throws InvalidDataException
     * @throws UnsupportedTagException
     * @throws IOException
     * @throws NotSupportedException
     */
    private static void changeTitleAndName(File file, String title) throws InvalidDataException, UnsupportedTagException, IOException, NotSupportedException {
        Mp3File mp3File = new Mp3File(file);
        String nameTemp = file.getName();
        ID3v2 tag;
        if (mp3File.hasId3v2Tag()) {
            tag = mp3File.getId3v2Tag();
        } else {
            tag = new ID3v23Tag();
            mp3File.setId3v2Tag(tag);
        }
        String name = FsUtils.getNameExcludingSuffix(mp3File.getFilename());
        tag.setTitle(title);
        mp3File.save(Paths.get(file.getParent(), name + SUFFIX).toString());
        file.delete();
        file = new File(mp3File.getFilename());
        file.renameTo(new File(nameTemp));
    }

    /**
     * 修改Title
     *
     * @param file MP3文件
     * @param title 新title
     * @throws InvalidDataException
     * @throws UnsupportedTagException
     * @throws IOException
     * @throws NotSupportedException
     */
    public static void changeTitle(File file, String title) throws InvalidDataException, UnsupportedTagException, IOException, NotSupportedException {
        String name = file.getAbsolutePath();
        changeTitleAndName(file, title);
        FsUtils.rename(Paths.get(FsUtils.getDirectory(name), FsUtils.getNameExcludingSuffix(name)+SUFFIX).toString(), name);
    }
}
